package marcopolo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

//消息处理器类
public class MarcoHandler extends AbstractWebSocketHandler {

	private static final Logger logger = LoggerFactory.getLogger(MarcoHandler.class);

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		logger.info("Received message: {}", message.getPayload());
		Thread.sleep(2000);
		session.sendMessage(new TextMessage("Polo!"));
	}

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		logger.info("Connection established");
		logger.info("session: {}", session);
		logger.info("extensions: {}", session.getExtensions());
		logger.info("attributes: {}", session.getAttributes());
		logger.info("acceptedProtocol: {}", session.getAcceptedProtocol());
		logger.info("principal: {}", session.getPrincipal());
		logger.info("localAddress: {}", session.getLocalAddress());
		logger.info("remoteAddress: {}", session.getRemoteAddress());
		logger.info("handshakeHeaders: {}", session.getHandshakeHeaders());
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		logger.info("Connection closed.Status: {}", status);
		super.afterConnectionClosed(session, status);
	}

	/*
	 * 除了重载WebSocketHandler中所定义的五个方法以外，
	 * 我们还可以重载AbstractWebSocketHandler中所定义的三个方法： handleBinaryMessage()
	 * handlePongMessage() handleTextMessage()
	 */

	/*
	 * 另外一种方案，我们可以扩展TextWebSocketHandler或BinaryWebSocketHandler，
	 * 用来定义如何处理文本或二进制消息，如果收到其他类型消息的时候，将会关闭WebSocket连接。
	 */

}
